package com.example.demo.controller;

import com.example.demo.config.error.BizException;
import com.example.demo.controller.dto.FlowPatientUpdateDTO;
import com.example.demo.controller.vo.ChatVO;
import com.example.demo.controller.vo.DoctorFlowVO;
import com.example.demo.dao.ChatDao;
import com.example.demo.dao.DoctorDao;
import com.example.demo.dao.FlowDao;
import com.example.demo.dao.PatientDao;
import com.example.demo.entity.Doctor;
import com.example.demo.entity.DoctorFlow;
import com.example.demo.entity.Flow;
import com.example.demo.entity.Chat;
import com.example.demo.utils.Result;
import com.example.demo.utils.ResultUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @Author: WinstonDeng
 * @Description:
 * @Date: Created in 10:18 2020/4/9
 * @Modified by:
 */
@RestController
@RequestMapping("/flow")
public class FlowController {
    @Autowired
    private FlowDao flowDao;

    @Autowired
    private DoctorDao doctorDao;

    @Autowired
    private PatientDao patientDao;

    @Autowired
    private ChatDao chatDao;

    @PostMapping("/updatePatient")
    @ResponseBody
    public ResponseEntity<Result> updatePatient(@RequestBody FlowPatientUpdateDTO flowPatientUpdateDTO) throws BizException {
        if(flowPatientUpdateDTO.getFlowId() == null){
            return ResponseEntity.ok(ResultUtil.error(417, "flowId 不能为空"));
        }
        Flow flow = flowDao.getById(flowPatientUpdateDTO.getFlowId());
        if (flow == null){
            return ResponseEntity.ok(ResultUtil.error(404, "未找到 flow"));
        }
        flow.setDescription(flowPatientUpdateDTO.getDesc());
        flow.setBedNum(flowPatientUpdateDTO.getBedNum());
        flow.setHospNum(flowPatientUpdateDTO.getHospNum());
        if(!flowPatientUpdateDTO.getFlowPatientName().isEmpty() || flowPatientUpdateDTO.getFlowPatientName() != null){
            flow.setFlowPatientName(flowPatientUpdateDTO.getFlowPatientName());
        }
        return ResponseEntity.ok(ResultUtil.success(flowDao.updateFlow(flow)));
    }

    /**
     * 推动流程，当前 flow_step 完成，下一个flow_step 正在进行
     * @return
     * @throws Exception
     */
    @PostMapping("/pushFlow/{flowId}")
    @ResponseBody
    public ResponseEntity<Result> updateFlow(@PathVariable("flowId") long flowId) throws BizException{
        Flow flow = flowDao.getById(flowId);
        if(flow == null){
            return ResponseEntity.ok(ResultUtil.error(404, "未找到 flow"));
        }
        if(flow.getState() == Flow.STATE_FINISH){
            return ResponseEntity.ok(ResultUtil.error(406, "该流程已结束，无需推进"));
        }else if (flow.getState() == Flow.STATE_BREAK){
            return ResponseEntity.ok(ResultUtil.error(406, "此 flow 已经中断，不可推进"));
        }
        return ResponseEntity.ok(ResultUtil.success(flowDao.pushFlow(flowId, flow.getDoctorId())));
    }

    // 新增流程中的默认模块
    @PostMapping("/insertFlow")
    @ResponseBody
    public ResponseEntity<Result> insertFlow(@RequestParam("doctorId") long  doctorId, @RequestParam("patientId") long patientId) throws BizException{
        return ResponseEntity.ok(ResultUtil.success(flowDao.insertFlow(doctorId, patientId)));
    }

    // 对已有流程添加额外自定义的模块
    @PostMapping("/addSteps/{flowId}")
    @ResponseBody
    public ResponseEntity<Result> addSteps(@PathVariable("flowId") long flowId, @RequestParam("templeteId") long templeteId) throws BizException{
        Flow flow = flowDao.getById(flowId);
        if(flow == null){
            return ResponseEntity.ok(ResultUtil.error(404, "未找到 flow"));
        }
        return ResponseEntity.ok(ResultUtil.success(flowDao.addSteps(flowId, templeteId)));
    }

    @GetMapping("/{flowId}")
    @ResponseBody
    public ResponseEntity<Result> getFlowById(@PathVariable("flowId") long flowId) throws BizException{
        return ResponseEntity.ok(ResultUtil.success(flowDao.getById(flowId)));
    }

    @GetMapping("/getByDoctor")
    @ResponseBody
    public ResponseEntity<Result> getFlowListByDoctorIdAndState(@RequestParam("doctorId") long doctorId, @RequestParam("state") String state) throws BizException{
        if(Integer.parseInt(state) == -1){
            List<Flow> flowList1 = flowDao.getListByDoctorIdAndState(doctorId, Flow.STATE_BREAK);
            List<Flow> flowList2 = flowDao.getListByDoctorIdAndState(doctorId, Flow.STATE_FINISH);
            flowList1.addAll(flowList2);
            return ResponseEntity.ok(ResultUtil.success(flowList1));
        }else {
            return ResponseEntity.ok(ResultUtil.success(flowDao.getListByDoctorIdAndState(doctorId, Integer.parseInt(state))));
        }
    }

    @GetMapping("/getByPatient")
    @ResponseBody
    public ResponseEntity<Result> getFlowListByPatientIdAndState(@RequestParam("patientId") long patientId, @RequestParam("state") String state) throws BizException{
        if(Integer.parseInt(state) == -1){
            List<Flow> flowList1 = flowDao.getListByPatientIdAndState(patientId, Flow.STATE_BREAK);
            List<Flow> flowList2 = flowDao.getListByPatientIdAndState(patientId, Flow.STATE_FINISH);
            flowList1.addAll(flowList2);
            return ResponseEntity.ok(ResultUtil.success(flowList1));
        }else {
            return ResponseEntity.ok(ResultUtil.success(flowDao.getListByPatientIdAndState(patientId, Integer.parseInt(state))));
        }
    }

    @GetMapping("/getFlowDoctor/{flowId}")
    @ResponseBody
    public ResponseEntity<Result> getFlowDoctorListByFlowId(@PathVariable("flowId") long flowId) throws BizException{
        List<DoctorFlow> doctorFlowList = flowDao.getFlowDoctorListByFlowId(flowId);
        List<DoctorFlowVO> doctorFlowVOList = new ArrayList<>();
        for(DoctorFlow doctorFlow:doctorFlowList){
            Doctor doctor = doctorDao.getById(doctorFlow.getDoctorId());
            DoctorFlowVO doctorFlowVO = new DoctorFlowVO();
            doctorFlowVO.setName(doctor.getRealName());
            doctorFlowVO.setHonor(doctor.getHonor());
            doctorFlowVO.setDescription(doctor.getDescription());
            doctorFlowVO.setDuty(doctorFlow.getDuty());
            doctorFlowVOList.add(doctorFlowVO);
        }
        Collections.sort(doctorFlowVOList);
        return ResponseEntity.ok(ResultUtil.success(doctorFlowVOList));
    }

    @PostMapping("/shutdown/{flowId}")
    @ResponseBody
    public ResponseEntity<Result> shutDownFlow(@PathVariable("flowId") long flowId) throws BizException{
        return ResponseEntity.ok(ResultUtil.success(flowDao.shutDownFlow(flowId)));
    }

    @PostMapping("/updateFlowScore/{flowId}")
    @ResponseBody
    public ResponseEntity<Result> updateFlowScore(@PathVariable("flowId") long flowId) throws BizException{
        return ResponseEntity.ok(ResultUtil.success(flowDao.updateFlowScore(flowId)));
    }

    @GetMapping("/getChatList/{flowId}")
    @ResponseBody
    public ResponseEntity<Result> getChatList(@PathVariable("flowId") long flowId) throws BizException{
        List<Chat> chatList = chatDao.getChatList(flowId);
        List<ChatVO> chatVOList = new ArrayList<>();
        for(Chat chat:chatList){
            long personId = chat.getPersonId();
            int role = chat.getRole();
            String name;
            String roleName;
            if(role==Chat.ROLE_DOCTOR){
                name = doctorDao.getById(personId).getRealName();
                roleName = "doctor";
            }else {
                name = patientDao.getById(personId).getRealName();
                roleName = "patient";
            }
            ChatVO chatVO = new ChatVO();
            chatVO.setName(name);
            chatVO.setPersonId(chat.getPersonId());
            chatVO.setRole(roleName);
            chatVO.setMessage(chat.getMessage());
            chatVO.setCreateTime(chat.getCreateTime());
            chatVOList.add(chatVO);
        }
        return ResponseEntity.ok(ResultUtil.success(chatVOList));
    }

    @PostMapping("/addChat/{flowId}")
    @ResponseBody
    public ResponseEntity<Result> addChat(@PathVariable("flowId") long flowId, @RequestBody Chat chat){
        Flow flow = flowDao.getById(flowId);
        if(flow == null){
            return ResponseEntity.ok(ResultUtil.error(404, "未找到 flow"));
        }
        chat.setFlowId(flowId);
        return ResponseEntity.ok(ResultUtil.success(chatDao.addChat(chat)));
    }
}
